package com.xiaoma.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoma.feign.ThirdPartyFeignService;
import com.xiaoma.service.UserService;
import entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import utils.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: xiaoma
 * @Date: 2021/7/8 14:01
 * @description:
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/list")
    public R login(@RequestBody User user, HttpSession session) {
//        User res = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
//        //SpringSession 后端全局共享登录用户
//        session.setAttribute("loginUser",res);
        String token = userService.login(user);
        if (token == null) return R.error();
        //生成token返回给前端
        return R.ok().put("token",token);
    }

    @GetMapping("/getSession")
    public void login(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        log.info(user.toString());
    }

    @GetMapping("/sendSms")
    public R register(@RequestParam String phone, HttpSession session) {
        //  接口防刷，redis缓存  phone:code_系统时间
        String redisCode = stringRedisTemplate.opsForValue().get(phone);
        // 如果不为空，返回错误信息
        if (null != redisCode && redisCode.length() > 0) {
            long CuuTime = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - CuuTime < 60 * 1000) { // 60s
                log.warn("60S内再次发送验证码");
                return R.error();
            }
        }
        // 生成验证码
        String code = UUID.randomUUID().toString().substring(0, 6);
        String redis_code = code + "_" + System.currentTimeMillis();
        // 缓存验证码
        stringRedisTemplate.opsForValue().set(phone, redis_code, 10, TimeUnit.MINUTES);
//        try {// 调用第三方短信服务
        return thirdPartyFeignService.sendCode(phone, code);
//        } catch (Exception e) {
//            log.warn("第三方短信服务错误");
//        }
    }

    @PostMapping("/register")
    public R register(@Valid @RequestBody User user, BindingResult result) {
        //判断JSR303校验是否通过
        if (result.hasErrors()) {
            log.info("错误信息{}", result);
            return R.error(1, "JSR303校验不通过");
        }
        //判断验证码是否正确
        String code = stringRedisTemplate.opsForValue().get(user.getPhone());
        //如果对应手机的验证码不为空且与提交的相等-》验证码正确
        if (!StringUtils.isEmpty(code) && user.getCode().equals(code.split("_")[0])) {
            //使得验证后的验证码失效
            stringRedisTemplate.delete(user.getPhone());
            //密码加密
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String encode = encoder.encode(user.getPassword());
            user.setPassword(encode);

            userService.save(user);
            return R.ok();
        } else {
            //验证码错误
            return R.error(1, "验证码错误");
        }

    }

}